package service

import (
	"egin/app/models"
	"egin/pkg/database"
	"egin/pkg/redigo"
	"encoding/json"
	"strconv"
	"strings"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"gorm.io/gorm"
)

//RbacCheck 检查权限
func RbacCheck(c *gin.Context) bool {
	session := sessions.Default(c)
	uid := session.Get("id")
	if uid.(string) == "1" {
		return true
	}
	conn := redigo.GetPool().Get()
	defer conn.Close()

	getjson, err := redis.Bytes(conn.Do("hget", "admin_rbac", uid))
	if err == nil {

		if len(getjson) > 0 {
			var lists = make(map[string]string)
			err := json.Unmarshal(getjson, &lists)
			if err == nil {
				return check(c, lists)
			}
		}
	}

	var list *models.Member
	database.Db().Preload("Role", func(db *gorm.DB) *gorm.DB {
		return db.Select("id").Preload("Permission", func(db *gorm.DB) *gorm.DB {
			return db.Select("id", "href")
		})
	}).Where("id = ?", uid).Find(&list)

	var lists = make(map[string]string)
	for _, v := range list.Role {
		for _, y := range v.Permission {

			lists[strconv.Itoa(int(y.ID))] = y.Href

		}
	}

	json, _ := json.Marshal(lists)
	conn.Do("hset", "admin_rbac", uid, json)

	return check(c, lists)
}

func check(c *gin.Context, list map[string]string) bool {
	url := c.Request.URL.Path
	url = strings.Trim(url, "/")
	url1 := url

	var v1 string

	for _, v := range list {
		v = strings.Trim(v, "/")

		if len(c.Params) > 0 {
			v1 = v
			for _, y := range c.Params {
				v1 = strings.ReplaceAll(v1, ":"+y.Key, y.Value)
				url1 = strings.ReplaceAll(url1, y.Value, "")
			}

			url1 = strings.Trim(url1, "/")
			if v1 == v {
				if v == url1 {
					return true
				}
			} else {
				if v1 == url {
					return true
				}
			}
		} else {
			if v == url {
				return true
			}
		}

	}

	return false
}
